<template>
	<div>
		<el-card class="!border-none mb-4" shadow="never">
			<div class="flex flex-wrap">
				<div class="w-1/2 md:w-1/5">
					<div class="leading-10">总余额</div>
					<div class="text-6xl">{{ pager.extend.total_money }}</div>
				</div>
				<div class="w-1/2 md:w-1/5">
					<div class="leading-10">总充值(成功)</div>
					<div class="text-6xl">{{ pager.extend.total_recharge }}</div>
				</div>
				<div class="w-1/2 md:w-1/5">
					<div class="leading-10">总提现(成功)</div>
					<div class="text-6xl">{{ pager.extend.total_withdraw }}</div>
				</div>
				<!-- <div class="w-1/2 md:w-1/5">
					<div class="leading-10">充提差(客损)</div>
					<div class="text-6xl">{{ pager.extend.recharge_withdraw }}</div>
				</div> -->
				<div class="w-1/2 md:w-1/5">
					<div class="leading-10">提现中</div>
					<div class="text-6xl">{{ pager.extend.withdraw_ing }}</div>
				</div>
				<div class="w-1/2 md:w-1/5">
					<div class="leading-10">充值中</div>
					<div class="text-6xl">{{ pager.extend.recharge_ing }}</div>
				</div>
			</div>
		</el-card>
		<el-card class="!border-none" shadow="never">
			<el-form ref="formRef" class="mb-[-16px]" :model="queryParams" :inline="true" label-width="auto">
				<el-form-item label="用户信息">
					<el-input class="w-[200px]" v-model="queryParams.user_info" placeholder="账号/邀请码" clearable
						@keyup.enter="resetPage" />
				</el-form-item>
				<!-- <el-form-item label="手机区号" prop="country_code">
					<el-select class="w-[200px]" v-model="queryParams.country_code" placeholder="请选择手机区号" clearable>
						<el-option v-for="item in optionsData.regioncode" :label="item.code" :value="item.code" />
					</el-select>
				</el-form-item> -->
				<el-form-item label="启用状态" prop="is_open">
					<el-select class="w-[200px]" v-model="queryParams.is_open" clearable placeholder="启用状态">
						<el-option label="全部" value=""></el-option>
						<el-option v-for="(item, index) in dictData.is_open" :key="index" :label="item.name"
							:value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="代理状态" prop="is_agent">
					<el-select class="w-[200px]" v-model="queryParams.is_agent" clearable placeholder="代理状态">
						<el-option label="全部" value=""></el-option>
						<el-option v-for="(item, index) in dictData.is_agent" :key="index" :label="item.name"
							:value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="会员等级" prop="member_id">
					<el-select class="w-[200px]" v-model="queryParams.member_id" placeholder="请选择会员等级" clearable>
						<el-option v-for="item in optionsData.vips" :key="item.id" :label="item.name"
							:value="item.id" />
					</el-select>
				</el-form-item>
				<!-- <el-form-item label="邮箱地址">
					<el-input class="w-[200px]" v-model="queryParams.email" placeholder="邮箱地址" clearable
						@keyup.enter="resetPage" />
				</el-form-item>
				<el-form-item label="邮箱认证" prop="auth_email">
					<el-select class="w-[200px]" v-model="queryParams.auth_email" clearable placeholder="邮箱认证">
						<el-option label="全部" value=""></el-option>
						<el-option v-for="(item, index) in dictData.auth_status" :key="index" :label="item.name"
							:value="item.value" />
					</el-select>
				</el-form-item> -->
				<el-form-item label="注册IP">
					<el-input class="w-[200px]" v-model="queryParams.register_ip" placeholder="注册IP" clearable
						@keyup.enter="resetPage" />
				</el-form-item>
				<el-form-item label="登录IP">
					<el-input class="w-[200px]" v-model="queryParams.login_ip" placeholder="登录IP" clearable
						@keyup.enter="resetPage" />
				</el-form-item>
				<!-- <el-form-item label="充值差范围" prop="recharge_withdraw_min">
					<el-input class="w-[200px]" v-model="queryParams.recharge_withdraw_min" clearable
						placeholder="充值差大于等于" />
				</el-form-item>
				<el-form-item label="充值差范围" prop="recharge_withdraw_max">
					<el-input class="w-[200px]" v-model="queryParams.recharge_withdraw_max" clearable
						placeholder="充值差小于等于" />
				</el-form-item> -->
				<el-form-item label="注册时间">
					<daterange-picker v-model:startTime="queryParams.create_time_start"
						v-model:endTime="queryParams.create_time_end" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="resetPage">查询</el-button>
					<el-button @click="resetParams">重置</el-button>
					<export-data v-perms="['user.user/export']" class="ml-2.5" :fetch-fun="getUserList"
						:params="queryParams" :page-size="pager.size" />
				</el-form-item>
			</el-form>
		</el-card>
		<el-card class="!border-none mt-4" shadow="never">
			<div>
				<el-button class="mb-4" v-perms="['user.user/add']" type="primary" @click="handleAdd()">
					<template #icon>
						<icon name="el-icon-Plus" />
					</template>
					新增
				</el-button>
				<el-button class="mb-4" v-perms="['user.user/notice']" type="warning" @click="handleSend(selectUsers)">
					发送消息
				</el-button>
				<el-button class="mb-4" v-perms="['user.user/caijin']" type="danger" @click="handleCaijin(selectUsers)">
					彩金赠送
				</el-button>
			</div>
			<el-table size="large" v-loading="pager.loading" :data="pager.lists" :row-class-name="tableRowClassName"
				@selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" />
				<el-table-column label="用户" min-width="200">
					<template #default="{ row }">
						<div v-copy="row.account">账号：{{row.mobile}}</div>
						<div>邀请码：{{row.sn}}</div>
						<div v-perms="['user.user/updateSnStatus']">启用邀请码：
							<el-switch size="small" v-model="row.is_sn" :active-value="1"
								:inactive-value="0" @change="changeSnStatus($event, row.id)" />
						</div>
						<div v-perms="['user.user/updateAgentStatus']" v-if="row.team_top.level ==''">开启代理：
							<el-switch size="small" v-model="row.is_agent"
								:active-value="1" :inactive-value="0" @change="changeAgentStatus($event, row.id)" />
						</div>
						<div v-perms="['user.user/updateOpenStatus']">启用禁用：
							<el-switch size="small" v-model="row.is_open"
								:active-value="1" :inactive-value="0" @change="changeOpenStatus($event, row.id)" />
						</div>
					</template>
				</el-table-column>
				<el-table-column label="用户详情" min-width="130" show-tooltip-when-overflow>
					<template #default="{ row }">
						<div class="flex">邮箱：
							<popover-input class="" @confirm="handleEmail($event, 'pwd',row.id)" :limit="32"
								placeholder="请输入邮箱" v-perms="['user.user/changeEmail']">
								<el-button type="primary" link>
									<icon name="el-icon-EditPen" />
								</el-button>
							</popover-input>
							<text>{{row.auth_email==1?row.email:""}}</text>
						</div>
						<div>会员等级：{{row.vip_name}}
							<el-button v-perms="['member.user_member/lists']" type="primary" link @click="handleMember(row.id)">
								<icon name="el-icon-EditPen" />
							</el-button>
						</div>
						<div v-perms="['user.user/updateMemberStatus']">自动升级：
							<el-switch size="small" v-model="row.auto_member"
								:active-value="1" :inactive-value="0" @change="changeMemberStatus($event, row.id)" />
						</div>
						<div v-perms="['user.user/updateTransferStatus']">开启转账：
							<el-switch size="small" v-model="row.is_transfer" :active-value="1"
								:inactive-value="0" @change="changeTransferStatus($event, row.id)" />
						</div>
						<!-- <div v-perms="['user.user/updateLhStatus']">开启量化：
							<el-switch size="small" v-model="row.is_lh" :active-value="1"
								:inactive-value="0" @change="changeLhStatus($event, row.id)" />
						</div> -->
					</template>
				</el-table-column>
				<el-table-column label="用户层级" min-width="130" show-tooltip-when-overflow>
					<template #default="{ row }">
						<div>上级：{{row.team_top.prev_account}}</div>
						<div>一代：{{row.team_top.top_account}}</div>
						<div v-if="row.team_top.top_name != ''">一代名称：{{row.team_top.top_name}}</div>
						<div>代数：{{row.team_top.level}}</div>
					</template>
				</el-table-column>
				<el-table-column label="资金情况" min-width="200" show-tooltip-when-overflow>
					<template #default="{ row }">
						<div>
							总资产：{{row.user_money}}
							<el-button v-perms="['user.user/adjustMoney']" type="primary" link
								@click="handleAdjust(row.user_money,row.id)">
								<icon name="el-icon-EditPen" />
							</el-button>
						</div>
						<!-- <div>待释放：{{row.unused_money}}</div> -->
						<div>总充值：{{row.total_recharge}}</div>
						<div>总提现：{{row.total_withdraw}}</div>
						<div>充提差：
							<span v-if="row.total_recharge - row.total_withdraw < 0"
								class="text-danger font-bold">{{row.total_recharge - row.total_withdraw}}</span>
							<span
								v-if="row.total_recharge - row.total_withdraw >= 0">{{row.total_recharge - row.total_withdraw}}</span>
						</div>
						<div>总积分：{{row.user_point}}</div>
					</template>
				</el-table-column>
				<el-table-column label="团队情况" min-width="130" show-tooltip-when-overflow>
					<template #default="{ row }">
						<div>团队人数：{{row.team_num}}</div>
						<div>团队充值：{{row.team_recharge}}</div>
						<div>团队提现：{{row.team_withdraw}}</div>
					</template>
				</el-table-column>
				<el-table-column label="推广情况" min-width="130" show-tooltip-when-overflow>
					<template #default="{ row }">
						<div v-for="item in row.team_report" :key="item.id">
							{{item.level}}级人数：
							<el-button type="primary" link @click="openRelation(row.sn,item.level)">
								{{item.num}}/{{item.num_valid}}
							</el-button>
						</div>
					</template>
				</el-table-column>
				<el-table-column label="质押情况" min-width="130" show-tooltip-when-overflow>
					<template #default="{ row }">
						<div>总订单：{{row.item_num}}</div>
						<div>今订单：{{row.today_item_num}}</div>
						<div>总收益：{{row.total_income_invest}}</div>
						<div>总质押：{{row.total_invest}}</div>
					</template>
				</el-table-column>
				<el-table-column label="挖矿情况" min-width="130" show-tooltip-when-overflow>
					<template #default="{ row }">
						<div>总收益：{{row.mine.total_income}}</div>
						<div>今收益：{{row.mine.today_income}}</div>
					</template>
				</el-table-column>
				<el-table-column label="时间" min-width="240" show-tooltip-when-overflow>
					<template #default="{ row }">
						<div>注册时间：{{row.create_time}}</div>
						<div>注册IP：{{row.register_ip}}
							<span class="text-danger font-bold"
								v-if="row.register_ip != '' && row.register_ip_num>1">({{row.register_ip_num}})</span>
						</div>
						<!-- <div>注册国家：{{row.register_country}}</div> -->
						<div>最后登录：{{row.login_time}}</div>
						<div>登录IP：{{row.login_ip}}
							<span class="text-danger font-bold"
								v-if="row.login_ip != '' && row.login_ip_num>1">({{row.login_ip_num}})</span>
						</div>
					</template>
				</el-table-column>
				<el-table-column label="操作" fixed="right" width="120">
					<template #default="{ row }">
						<div class="flex justify-start">
							<el-button v-perms="['user.user/adjustMoney']" type="primary" link
								@click="handleAdjust(row.user_money,row.id)">
								余额调整
							</el-button>
						</div>
						<div class="flex justify-start">
							<popover-input class="" @confirm="handlePwd($event, 'pwd',row.id)" :limit="32"
								placeholder="请输入登录密码" v-perms="['user.user/changePwd']">
								<el-button type="primary" link>
									修改登录密码
								</el-button>
							</popover-input>
						</div>
						<div class="flex justify-start">
							<el-button v-perms="['user.user/resetPayPwd']" type="primary" link
								@click="handleResetPwd(row.id)">
								重置交易密码
							</el-button>
						</div>
						<div class="flex justify-start">
							<el-button v-perms="['user.user/resetEmail']" type="primary" link
								@click="handleResetEmail(row.id)">
								重置邮箱验证
							</el-button>
						</div>
						<div class="flex justify-start">
							<el-button v-perms="['user.user/resetGoogle']" type="primary" link
								@click="handleResetGoogle(row.id)">
								重置谷歌验证
							</el-button>
						</div>

					</template>
				</el-table-column>
			</el-table>
			<div class="flex justify-end mt-4">
				<pagination v-model="pager" @change="getLists" />
			</div>
		</el-card>
		<add-popup v-if="showAdd" ref="addRef" @success="getLists" @close="showAdd = false" />
		<account-adjust v-model:show="adjustState.show" :value="adjustState.value" @confirm="handleConfirmAdjust" />
		<member-popup v-if="showMember" ref="memberRef" @success="getLists" @close="showMember = false" />
		<notice-popup v-if="showNotice" ref="noticeRef" @success="getLists" @close="showNotice = false" />
		<caijin-popup v-if="showCaijin" ref="caijinRef" @success="getLists" @close="showCaijin = false" />
		<relation-popup v-if="showRelation" ref="relationRef" @close="showRelation = false" />
	</div>
</template>
<script lang="ts" setup name="consumerLists">
	import { usePaging } from '@/hooks/usePaging'
	import { getUserList, adjustMoney, changePwd, resetPayPwd, updateMemberStatus, updateLhStatus, updateOpenStatus, updateAgentStatus, changeAgentName, updateSnStatus, changeEmail, resetEmail, resetGoogle, remark,updateTransferStatus } from '@/api/consumer'
	import { isEmpty } from '@/utils/util'
	import { useDictData, useDictOptions } from '@/hooks/useDictOptions'
	import { apiUserMemberAll } from '@/api/user_member'
	import { apiRegioncodeAll } from '@/api/setting/website'
	import AddPopup from './add.vue'
	import AccountAdjust from '../components/account-adjust.vue'
	import MemberPopup from '../components/member.vue'
	import NoticePopup from '../components/notice.vue'
	import CaijinPopup from '../components/caijin.vue'
	import RelationPopup from '../components/relation.vue'
	import feedback from '@/utils/feedback'

	const addRef = shallowRef<InstanceType<typeof AddPopup>>()
	const memberRef = shallowRef<InstanceType<typeof MemberPopup>>()
	const noticeRef = shallowRef<InstanceType<typeof NoticePopup>>()
	const caijinRef = shallowRef<InstanceType<typeof CaijinPopup>>()
	const relationRef = shallowRef<InstanceType<typeof RelationPopup>>()

	const showNotice = ref(false)
	const showAdd = ref(false)
	const showMember = ref(false)
	const showCaijin = ref(false)
	const showRelation = ref(false)

	const queryParams = reactive({
		sn: '',
		user_info: '',
		country_code: '',
		member_id: '',
		email: '',
		auth_email: '',
		is_open: '',
		is_agent: '',
		recharge_withdraw_min: '',
		recharge_withdraw_max: '',
		register_ip: '',
		login_ip: '',
		create_time_start: '',
		create_time_end: '',
		parent_sn: '',
		level: ''
	})

	const adjustState = reactive({
		show: false,
		value: '',
		id: 0
	})

	const { optionsData } = useDictOptions<{
		vips : any[]
		regioncode : any[]
	}>({
		vips: {
			api: apiUserMemberAll
		},
		regioncode: {
			api: apiRegioncodeAll
		}
	})

	// 获取字典数据
	const { dictData } = useDictData('auth_status,is_open,is_agent')

	const { pager, getLists, resetPage, resetParams } = usePaging({
		fetchFun: getUserList,
		params: queryParams
	})
	// 选中数据
	const selectData = ref<any[]>([])
	const selectUsers = ref<any[]>([])

	// 表格选择后回调事件
	const handleSelectionChange = (val : any[]) => {
		selectData.value = val.map(({ id }) => id)
		selectUsers.value = val.map(({ account }) => account)
	}
	onActivated(() => {
		getLists()
	})
	const handleAdd = async () => {
		showAdd.value = true
		await nextTick()
		addRef.value?.open('add')
	}
	const handleSend = async (account : number | any[]) => {
		showNotice.value = true
		await nextTick()
		noticeRef.value?.open()
		noticeRef.value?.setFormData({ account })
	}
	const handleCaijin = async (account : number | any[]) => {
		showCaijin.value = true
		await nextTick()
		caijinRef.value?.open()
		caijinRef.value?.setFormData({ account })
	}
	const handleAdjust = (value : string, id : number) => {
		adjustState.show = true
		adjustState.value = value
		adjustState.id = id
	}
	const handleMember = async (id : number) => {
		showMember.value = true
		await nextTick()
		memberRef.value?.open()
		memberRef.value?.setFormData({ user_id: id })
	}
	const openRelation = async (sn : string, level : number) => {
		showRelation.value = true
		await nextTick()
		relationRef.value?.open()
		relationRef.value?.setFormData({ level: level, sn: sn })
	}
	const handleConfirmAdjust = async (value : any) => {
		await adjustMoney({ user_id: adjustState.id, ...value })
		adjustState.show = false
		getLists()
	}

	const handlePwd = async (value : string, field : string, id : number) => {
		if (isEmpty(value)) return
		await changePwd({ id: id, pwd: value })
	}

	const handleEmail = async (value : string, field : string, id : number) => {
		if (isEmpty(value)) {
			return feedback.msgError('请输入正确的邮箱地址')
		}
		var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
		if (!emailRegex.test(value)) {
			return feedback.msgError('请输入正确的邮箱地址')
		}
		await changeEmail({ id: id, email: value })
		getLists()
	}

	const handleResetPwd = async (id : number) => {
		await feedback.confirm('确定要重置交易密码吗？')
		await resetPayPwd({ id })
		// getLists()
	}

	const handleResetEmail = async (id : number) => {
		await feedback.confirm('确定要重置邮箱验证吗？')
		await resetEmail({ id })
		getLists()
	}

	const handleResetGoogle = async (id : number) => {
		await feedback.confirm('确定要重置谷歌验证吗？')
		await resetGoogle({ id })
	}

	const changeMemberStatus = async (auto_member : any, id : number) => {
		await updateMemberStatus({ id, auto_member })
		// getLists()
	}

	// const changeLhStatus = async (is_lh : any, id : number) => {
	// 	await updateLhStatus({ id, is_lh })
	// 	// getLists()
	// }
	
	const changeTransferStatus = async (is_transfer : any, id : number) => {
		await updateTransferStatus({ id, is_transfer })
		// getLists()
	}
	

	const changeOpenStatus = async (is_open : any, id : number) => {
		await updateOpenStatus({ id, is_open })
		// getLists()
	}

	const changeAgentStatus = async (is_agent : any, id : number) => {
		await updateAgentStatus({ id, is_agent })
		// getLists()
	}

	const changeSnStatus = async (is_sn : any, id : number) => {
		await updateSnStatus({ id, is_sn })
		// getLists()
	}
	const handleRemark = async (value : string, field : string, id : number) => {
		if (isEmpty(value)) {
			value = ''
		}
		await remark({ id: id, content: value })
		getLists()
	}
	const handleAgentName = async (value : string, field : string, id : number) => {
		if (isEmpty(value)) {
			value = ''
		}
		await changeAgentName({ id: id, name: value })
		getLists()
	}

	const tableRowClassName = ({ row, rowIndex, } : {
		row : any
		rowIndex : number
	}) => {
		if (row['remark2'] != "") {
			return 'warning-row'
		}
		return ''
	}

	getLists()
</script>
<style>
	.el-table .warning-row {
		--el-table-tr-bg-color: var(--el-color-warning-light-9);
	}

	.el-table .success-row {
		--el-table-tr-bg-color: var(--el-color-success-light-9);
	}
</style>